package com.example.swd1.gudong.main.sport;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.example.swd1.gudong.R;
import com.example.swd1.gudong.constant.Constant;
import com.example.swd1.gudong.main.MainActivity;
import com.example.swd1.gudong.main.sport.normalsport.DoingSportActivity;
import com.example.swd1.gudong.main.sport.normalsport.MapTest;
import com.example.swd1.gudong.main.sport.normalsport.NormalSportFragment;
import com.example.swd1.gudong.main.sport.targetsport.TargetSportFragment;
import com.example.swd1.gudong.main.sport.trainplan.TrainPlanFragment;
import com.example.swd1.gudong.main.test.TestActivity;
import com.example.swd1.gudong.view.SearchingGpsDialog;
import com.example.swd1.gudong.view.StartView;

import java.util.ArrayList;
import java.util.List;

//==================================================================================================================
//   Author :  Shile Wu
//   Date  :  16-8-19
//   Role :   the view in sport fragment
//   Reference documents : xx
//==================================================================================================================
public class SportFragment extends Fragment implements ViewPager.OnPageChangeListener, StartView.onButtonClickListener, Animation.AnimationListener, LocationSource, AMapLocationListener {
    private ViewPager sportViewPager;
    private SportViewPageAdapter adapter;
    private NormalSportFragment normalSportFragment;
    private TargetSportFragment targetSportFragment;
    private TrainPlanFragment trainPlanFragment;
    private List<Fragment> fragmentList;
    private MainActivity activity;
    private StartView startLayout;
    private ImageView countImg, countImgBackground;
    private Animation countRotateAnimation;
    private Animation countFadeAnimation;
    private Animation backgroundScareAnimation;
    private int currentAnimation = 1;
    private RelativeLayout parentPanel;
    private LinearLayout linearLayout;
    private SearchingGpsDialog dialog;
    private static boolean canRunInBackground = true;
    private Location location;
    private boolean getGps = false;
    private static int FLAG_NO_PERMISSION = 1;
    private static int FLAG_NO_PROVIDER = 0;

    private AMap aMap;
    private MapView mapView;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private AMapLocation aMapLocation;
    private LatLng latLng;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (MainActivity) getActivity();
        init(savedInstanceState);
    }

    private void init(Bundle savedInstanceState) {
        mapView = new MapView(activity);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        aMap = mapView.getMap();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sport, container, false);
        sportViewPager = (ViewPager) view.findViewById(R.id.sport_view_page);

        startLayout = (StartView) view.findViewById(R.id.startLayout);
        startLayout.setOnButtonClickListener(this);
        countImg = (ImageView) view.findViewById(R.id.img_count);
        countImgBackground = (ImageView) view.findViewById(R.id.img_count_background);
        parentPanel = (RelativeLayout) view.findViewById(R.id.parentPanel);
        linearLayout = (LinearLayout) view.findViewById(R.id.linear_layout);

        normalSportFragment = new NormalSportFragment();
        targetSportFragment = new TargetSportFragment();
        trainPlanFragment = new TrainPlanFragment();
        fragmentList = new ArrayList<Fragment>();
        fragmentList.add(normalSportFragment);
        fragmentList.add(trainPlanFragment);
        fragmentList.add(targetSportFragment);
        adapter = new SportViewPageAdapter(getActivity().getSupportFragmentManager(), fragmentList);
        sportViewPager.setAdapter(adapter);
        sportViewPager.setOnPageChangeListener(this);
        return view;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        activity.setCurrentFragmentInSport(position + Constant.VIEW_PAGE_FLAG_SPORT);
        switch (position) {
            case 0:
                activity.changeTitleAndMenu(Constant.VIEW_PAGE_FLAG_SPORT);
                startLayout.setText("开始跑步");
                startLayout.setClickable(true);
                break;
            case 1:
                activity.changeTitleAndMenu(Constant.VIEW_PAGE_FLAG_TRAIN);
                startLayout.setText("开始训练");
                startLayout.setClickable(false);
                break;
            case 2:
                activity.changeTitleAndMenu(Constant.VIEW_PAGE_FLAG_TARGET);
                startLayout.setText("开始跑步");
                startLayout.setClickable(true);
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick() {
        startActivity(new Intent(getContext(), TestActivity.class));
//        canRunInBackground = true;
//        dialog = new SearchingGpsDialog(getActivity(), 260, 280, R.style.dialog);
//        dialog.setOnClickListener(new SearchingGpsDialog.OnclickListener() {
//                                      @Override
//                                      public void onClick(int id) {
//                                          switch (id) {
//                                              case R.id.btn_keep_sporting:
//                                                  dialog.dismiss();
////                                                  currentAnimation = 1;
////                                                  startbackgroundScareAnimation();
//                                                  canRunInBackground = false;
//                                                  break;
//                                              case R.id.btn_cancle:
//                                                  dialog.dismiss();
//                                                  canRunInBackground = false;
//                                                  if (mlocationClient != null) {
//                                                      mlocationClient.stopLocation();
//                                                  }
//                                                  break;
//                                          }
//                                      }
//                                  }
//        );
//        if (!dialog.isShowing()) {
//            dialog.show();
//        }
//
//        startSearchingGpsTask();
    }

    private void startSearchingGpsTask() {
        Thread thread;
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    Message message = new Message();
                    message.what = FLAG_NO_PERMISSION;
                    mHandler.sendMessage(message);
                } else {
                    aMap.setLocationSource(SportFragment.this);// 设置定位监听
                    aMap.setMyLocationEnabled(true);
                }
            }

        });
        thread.start();
    }

    private void startbackgroundScareAnimation() {
        countImgBackground.setVisibility(View.VISIBLE);
        backgroundScareAnimation = AnimationUtils.loadAnimation(activity, R.anim.count_background_scare_anim);
        backgroundScareAnimation.setAnimationListener(this);
        countImgBackground.startAnimation(backgroundScareAnimation);
    }

    private void startRotateAnimation(int currentAnimation) {
        switch (currentAnimation) {
            case 1:
                countImg.setImageDrawable(getResources().getDrawable(R.drawable.counter_3));
                break;
            case 2:
                countImg.setImageDrawable(getResources().getDrawable(R.drawable.counter_2));
                break;
            case 3:
                countImg.setImageDrawable(getResources().getDrawable(R.drawable.counter_1));
                break;
        }
        countImg.setVisibility(View.VISIBLE);
        countRotateAnimation = AnimationUtils.loadAnimation(activity, R.anim.count_rotate_and_scale_anim);
        countRotateAnimation.setAnimationListener(this);
        countImg.startAnimation(countRotateAnimation);
    }

    private void startFadeAnimation() {
        countFadeAnimation = AnimationUtils.loadAnimation(activity, R.anim.count_fade_anim);
        countFadeAnimation.setAnimationListener(this);
        countImg.startAnimation(countFadeAnimation);
    }


    @Override
    public void onAnimationStart(Animation animation) {
    }

    @Override
    public void onAnimationEnd(Animation animation) {
//        countImg.setVisibility(View.GONE);
        if (currentAnimation < 3) {
            if (animation == countRotateAnimation) {
                startFadeAnimation();
            } else if (animation == countFadeAnimation) {
                startRotateAnimation(++currentAnimation);
            } else if (animation == backgroundScareAnimation) {
                startRotateAnimation(1);
                countImgBackground.setVisibility(View.GONE);
                activity.hideFootAndHead();
                linearLayout.setVisibility(View.INVISIBLE);
                parentPanel.setBackgroundColor(getResources().getColor(R.color.codoon_no_alpha_green));
            }
        } else {
            countImg.setVisibility(View.GONE);
            Intent intent = new Intent(activity, DoingSportActivity.class);
            intent.putExtra("latLng",latLng);
            startActivity(intent);
            getActivity().finish();
        }
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == FLAG_NO_PERMISSION) {
                Toast.makeText(getActivity(), "no permission,pleas allow get you location and try again", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            } else if (msg.what == FLAG_NO_PROVIDER) {
                Toast.makeText(getActivity(), "no location provider,pleas choose one less provider and try again", Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        activity.showFootAndHead();
        linearLayout.setVisibility(View.VISIBLE);
        parentPanel.setBackgroundColor(getResources().getColor(R.color.codoon_gray_line));
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(activity);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            Log.d("555log", aMapLocation.getAltitude() + "," + aMapLocation.getLatitude());
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                //get the location and start next activity
                dialog.dismiss();
                this.aMapLocation = aMapLocation;
                latLng = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
                startbackgroundScareAnimation();
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }
}


